/*
 * RegionBuilder.cpp
 *
 *  Created on: 2009-8-23
 *      Author: ws
 */

#include "RegionBuilder.hpp"
#include"BlockImpl.hpp"
#include"Node.hpp"

RegionBuilder::~RegionBuilder(){

}

void RegionBuilder::build_new_ctrflow(Region* from, Region *to)
{
	CtrFlow * cf = new CtrFlow(from, to);
	from->outflows.push_back(cf);
	to->inflows.push_back(cf);
}


Region *RegionBuilder::build_new_region(BlockImpl * cb)
{
	Region *new_Region = new Region();
	cb->build_nodelist(new_Region->node_list);

	Operation<START_NODE> * start_node = cb->build_startnode();
	new_Region->node_list.push_front(start_node);
	new_Region->start_node = start_node;

	Operation<END_NODE>* end_node = cb->build_endnode();
	new_Regioni->node_list.push_back(end_node);
	new_Region->end_node = end_node;

	for(NodeSequence::iterator it = new_Region->node_list.begin(); it != new_Region->node_list.end(); it++)
	{
		(it)->init_defs_and_uses();
	}
	//check all out_flow
	BlockImpl::FlowInfo * flow = NULL;
	for(flow = cb->get_src_flow(); flow != NULL; flow = flow->get_next())
	{
		if(table.find(flow->get_src_id()) != table.end())
		{
			build_new_ctrflow(table[flow->get_src_id()], new_Region);
		}
	}
	//note: this code  must be placed after srcflow is builded in the reason for loop ctrflow
	table[cb->getID()] = new_Region;
	for(flow = cb->get_dest_flow(); flow != NULL; flow = flow->get_next())
	{
		if(table.find(flow->get_dest_id()) != table.end())
		{
			build_new_ctrflow(new_Region , table[flow->get_dest_id()]);
		}
	}

	new_Region->prev = last;
	if(last != NULL)
	{
		last->next  = new_Region;
	}
	last = new_Region;
	last->next = NULL;
	return new_Region;
}
